package com.ygqh.baby.service.trustone;

import com.alibaba.fastjson.JSON;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.model.WeixinPayAccount;
import com.ygqh.baby.ao.AppType;
import com.ygqh.baby.ao.BusinessModule;
import com.ygqh.baby.ao.PayType;
import com.ygqh.baby.exception.YgHttpException;
import com.ygqh.baby.model.OrderTaxes;
import com.ygqh.baby.po.YgOrderPayment;
import com.ygqh.baby.service.YgFrameCodeService;
import com.ygqh.baby.service.YgOrderDetailService;
import com.ygqh.baby.service.YgOrderPaymentService;
import com.ygqh.baby.service.alipay.api.AlipayApi;
import com.ygqh.baby.service.alipay.api.DeclareCustomsModel;
import com.ygqh.baby.service.trustone.model.YgDeclareCustomsResult;
import com.ygqh.baby.service.wechat.WxConfig;
import com.ygqh.baby.service.wechat.api.CustomsApi;
import com.ygqh.baby.service.wechat.model.DeclareCustomsResult;
import com.ygqh.baby.service.wechat.model.WxCustomDelarereDeclare;
import com.ygqh.baby.service.wechat.model.WxDeclareCustoms;
import com.ygqh.baby.service.wechat.model.WxQueryCustoms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;

@Component
public class YgCustomsApi {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private YgOrderPaymentService ygOrderPaymentService;
    @Autowired
    private AlipayApi alipayApi;
    @Autowired
    private YgFrameCodeService ygFrameCodeService;
    @Autowired
    private CustomsApi wxCustomsApi;
    @Autowired
    private YgOrderDetailService ygOrderDetailService;


    public Object queryCustoms(Long orderId) {
        YgOrderPayment orderPayment = ygOrderPaymentService.findByOrderId(orderId);

        if (PayType.Alipay.equals(orderPayment.getPayType())) {
            return null;

        } else if (PayType.WeChat.equals(orderPayment.getPayType())) {
            WeixinPayAccount wxPayAccount = AppType.WeChat.equals(orderPayment.getAppType()) ? WxConfig.getWxpayaccount() : WxConfig.getSmallpayaccount();

            WxQueryCustoms queryCustoms = new WxQueryCustoms();
            queryCustoms.setTransactionId(orderPayment.getTransactionId());
            queryCustoms.setCustoms(WxQueryCustoms.XINZHENGZHONGBAO_ZONGSHUBAN);
            //			queryCustoms.setMchCustomsNo(TrustoneConfig.getMerchantcustomscode());
            return wxCustomsApi.queryCustoms(queryCustoms, wxPayAccount);
        }
        return null;

    }

    public YgDeclareCustomsResult declareCustoms(Long orderId, String identityNo, String name) {
        YgOrderPayment orderPayment = ygOrderPaymentService.findByOrderId(orderId);
        //		if(!PayType.Alipay.equals(orderPayment.getPayType()) && !PayType.WeChat.equals(orderPayment.getPayType())){
        if (!PayType.WeChat.equals(orderPayment.getPayType())) {
            logger.warn("订单：" + orderId + " 支付方式无法报关。" + orderPayment.getPayType());
            YgDeclareCustomsResult result = new YgDeclareCustomsResult();
            result.setMsg("订单：" + orderId + " 支付方式无法报关。" + orderPayment.getPayType());
            result.setSuccess(false);
            return result;
        }

        OrderTaxes orderTaxes = ygOrderDetailService.getOrderTaxes(orderId);
        //税后金额：跨境电商综合税
        //		BigDecimal amount = orderPayment.getPaidPrice().subtract(orderTaxes.getTariff());

        return this.declareCustomsByWx(orderPayment, orderTaxes.getTariff(), identityNo, name);

    }

    //TODO 先推送HENAN报送地方国检，5分钟后再推送ZONGSHU  这里需要调整 （暂不支持支付宝报关。支付宝商户行业不支持）
    private void declareCustomsByAlipay(String outRequestNo, String transactionId, BigDecimal amount, String customsPlace) {
        DeclareCustomsModel declareCustoms = new DeclareCustomsModel();
        declareCustoms.setTradeNo(transactionId);
        declareCustoms.setMerchantCustomsCode(TrustoneConfig.getMerchantcustomscode());
        declareCustoms.setMerchantCustomsName("郑州航空港区全速通供应链管理有限公司");
        declareCustoms.setAmount(amount.toString());
        declareCustoms.setOutRequestNo(outRequestNo);
        declareCustoms.setCustomsPlace(customsPlace);
        try {
            alipayApi.declareCustoms(declareCustoms);
        } catch (YgHttpException e) {
            logger.error("支付宝：申报海关失败。 {}", JSON.toJSONString(declareCustoms));
            e.printStackTrace();
        }
    }

    private YgDeclareCustomsResult declareCustomsByWx(YgOrderPayment orderPayment, BigDecimal duty, String identityNo, String name) {
        WxDeclareCustoms wxCustoms = new WxDeclareCustoms();
        wxCustoms.setOutTradeNo(orderPayment.getOrderPayCode());
        wxCustoms.setTransactionId(orderPayment.getTransactionId());
        wxCustoms.setCustoms(WxDeclareCustoms.XINZHENGZHONGBAO_ZONGSHUBAN);
        wxCustoms.setMchCustomsNo(TrustoneConfig.getMerchantcustomscode());
        wxCustoms.setDuty(duty.multiply(new BigDecimal("100")).intValue());
        wxCustoms.setActionType("ADD");
        wxCustoms.setCertId(identityNo);
        wxCustoms.setName(name);
        wxCustoms.setCertType("IDCARD");
        WeixinPayAccount wxPayAccount = AppType.WeChat.equals(orderPayment.getAppType()) ? WxConfig.getWxpayaccount() : WxConfig.getSmallpayaccount();
        YgDeclareCustomsResult result = new YgDeclareCustomsResult();
        try {
            DeclareCustomsResult declareCustoms = wxCustomsApi.declareCustoms(wxCustoms, wxPayAccount);
            YgOrderPayment ygOrderPayment = new YgOrderPayment();
            ygOrderPayment.setOrderId(orderPayment.getOrderId());
            ygOrderPayment.setBusinessModule(BusinessModule.DeclareCustoms);
            ygOrderPayment.setOrderPayCode(declareCustoms.getOutTradeNo());
            ygOrderPayment.setPaidPrice(new BigDecimal(0));
            ygOrderPayment.setPrice(duty);
            ygOrderPayment.setPayType(PayType.WeChat);
            ygOrderPayment.setAppType(orderPayment.getAppType());
            ygOrderPayment.setCreateTime(new Date());
            ygOrderPayment.setPaidPrice(duty);
            ygOrderPayment.setPaySuccessTime(new Date());
            ygOrderPayment.setTransactionId(declareCustoms.getTransactionId());
            ygOrderPayment.setRemark(declareCustoms.getState());

            ygOrderPaymentService.save(ygOrderPayment);
            result.setSuccess(true);
            result.setOrderId(Long.parseLong(orderPayment.getOrderId()));
            result.setOutTradeNo(declareCustoms.getOutTradeNo());
            result.setTransactionId(declareCustoms.getTransactionId());
        } catch (WeixinException e) {
            result.setSuccess(false);
            result.setMsg(e.getMessage());
            logger.error("微信：申报海关失败。 {}", JSON.toJSONString(wxCustoms));
            e.printStackTrace();
        }
        result.setPayType(orderPayment.getPayType());
        return result;
    }

    /**
     * 微信订单附加信息重推接口
     *
     * @param orderPayCode
     * @param apyAppType
     * @return YgDeclareCustomsResult
     */
    public YgDeclareCustomsResult customDelarereDeclareByWx(String orderPayCode, AppType apyAppType) {
        WxCustomDelarereDeclare delarereDeclare = new WxCustomDelarereDeclare();
        delarereDeclare.setOutTradeNo(orderPayCode);
        delarereDeclare.setCustoms(WxDeclareCustoms.XINZHENGZHONGBAO_ZONGSHUBAN);
        delarereDeclare.setMchCustomsNo(TrustoneConfig.getMerchantcustomscode());
        delarereDeclare.setActionType("MODIFY");

        WeixinPayAccount wxPayAccount = AppType.WeChat.equals(apyAppType) ? WxConfig.getWxpayaccount() : WxConfig.getSmallpayaccount();

        YgDeclareCustomsResult result = new YgDeclareCustomsResult();
        try {
            DeclareCustomsResult declareCustomsResult = wxCustomsApi.declareDeclareCustoms(delarereDeclare, wxPayAccount);
            result.setSuccess(true);
            result.setOutTradeNo(declareCustomsResult.getOutTradeNo());
            result.setTransactionId(declareCustomsResult.getTransactionId());
        } catch (WeixinException e) {
            result.setSuccess(false);
            result.setMsg(e.getMessage());
            e.printStackTrace();
            logger.error("微信：附加信息重新申报海关失败。 {}", JSON.toJSONString(delarereDeclare));
        }
        return result;
    }

    public YgDeclareCustomsResult customDelarereModifyByWx(String orderPayCode, String transactionId, AppType apyAppType) {
        WxDeclareCustoms wxCustoms = new WxDeclareCustoms();
        wxCustoms.setOutTradeNo(orderPayCode);
        wxCustoms.setTransactionId(transactionId);
        wxCustoms.setCustoms(WxDeclareCustoms.XINZHENGZHONGBAO_ZONGSHUBAN);
        wxCustoms.setMchCustomsNo(TrustoneConfig.getMerchantcustomscode());
        wxCustoms.setActionType("MODIFY");

        WeixinPayAccount wxPayAccount = AppType.WeChat.equals(apyAppType) ? WxConfig.getWxpayaccount() : WxConfig.getSmallpayaccount();

        YgDeclareCustomsResult result = new YgDeclareCustomsResult();
        try {
            DeclareCustomsResult declareCustomsResult = wxCustomsApi.declareCustoms(wxCustoms, wxPayAccount);
            result.setSuccess(true);
            result.setOutTradeNo(declareCustomsResult.getOutTradeNo());
            result.setTransactionId(declareCustomsResult.getTransactionId());
        } catch (WeixinException e) {
            result.setSuccess(false);
            result.setMsg(e.getMessage());
            e.printStackTrace();
            logger.error("微信：重新申报海关失败。 {}", JSON.toJSONString(wxCustoms));
        }
        return result;
    }


}
